package pers.xuehongyan.useat.server.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import pers.xuehongyan.useat.server.enity.Ticket;
import pers.xuehongyan.useat.server.exception.ServiceException;
import pers.xuehongyan.useat.server.service.SeatService;

import javax.annotation.Resource;

/**
 * @author xuehongyan
 */
@RestController
@CrossOrigin(origins = {"*", "null"})
@RequestMapping("/seat")
public class SeatController {
    @Resource
    SeatService seatService;

    @PostMapping("/rent")
    public ResponseEntity<String> rent(
            @RequestParam("seat_id") Integer seatId,
            @RequestParam("token") String userToken
    ) {
        try {
            return ResponseEntity.ok(seatService.rent(seatId, userToken));
        } catch (ServiceException e) {
            return ResponseEntity.status(e.getHttpStatus()).body(e.getMessage());
        }
    }

    @PostMapping("/give_back")
    public ResponseEntity<Ticket> giveBack(
            @RequestParam("machine_id") Integer machineId,
            @RequestParam("token") String userToken,
            @RequestParam("totp") String totp
    ) {
        try {
            return ResponseEntity.ok(seatService.giveBack(machineId, userToken, totp));
        } catch (ServiceException e) {
            return ResponseEntity.status(e.getHttpStatus()).build();
        }
    }

    @PostMapping("/")
    public ResponseEntity<Integer> create(
            @RequestParam("machine_id") Integer machineId,
            @RequestParam("secret") String secret
    ) {
        try {
            return ResponseEntity.status(HttpStatus.CREATED).body(seatService.createSeat(machineId, secret));
        } catch (ServiceException e) {
            return ResponseEntity.status(e.getHttpStatus()).build();
        }
    }
}
